export default {
	namespaced: true,
	state:() => ({
		// 购物车的数组，用来存储购物车中每个商品的信息对象
		// 每个商品的信息对象，都包含如下 6 个属性：
		// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
		cart: JSON.parse(uni.getStorageSync('cart')||'[]'),
	}),
	
	//要改变state的数据
	mutations:{
		addToCart(state,goods){
			let findResult = state.cart.find((item)=> item.goods_id === goods.goods_id) 
			
			if(findResult){ //如果查询到了数量递增+1
				findResult.goods_count++ //返回的是对象,所以改变findResult的属性值原数组也会跟着改变
			}else{
				state.cart.push(goods)
			}
			
			this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		},
		updateGoodsState(state,data){
			for (let item of state.cart) {
				if(item.goods_id === data.goodsId){
					item.goods_state = data.goodsState
					this.commit('m_cart/saveToStorage')
					return 
				}
			}
		},
		updateGoodsCount(state,goodsItem){
			let item = state.cart.find(item=> item.goods_id === goodsItem.goods_id)
			if(item){
				item.goods_count = goodsItem.num  //返回的是对象,所以改变findResult的属性值原数组也会跟着改变
				this.commit('m_cart/saveToStorage')
			}
		},
		//根据id删除单个
		removeGoodsById(state,goodsId){
			state.cart = state.cart.filter(item=> item.goods_id !== goodsId)
			this.commit('m_cart/saveToStorage')
		},
		removeMulti(state,goods){
			state.cart = goods.filter(item=> item.goods_state === false)
			this.commit('m_cart/saveToStorage')
		},
		isAllCheck(state,is){ //全选/全不选
			state.cart.forEach(item=> item.goods_state = is)
			this.commit('m_cart/saveToStorage')
		}
	},
	
	getters:{
		total(state){ //计算购物车中的总数
			return state.cart.reduce((total,item)=> total+=item.goods_count,0)
		},
		checkedCount(state){ //计算选中的总数
			return state.cart.filter(item=> item.goods_state).reduce((total,item)=> total+=item.goods_count ,0)
		},
		checkedNum(state){ //计算选中的单体个数
			return state.cart.filter(item=> item.goods_state).length
		},
		checkSum(state){ //计算选中的总金额
			console.log(state.cart)
			return state.cart.filter(item=> item.goods_state).reduce((total,item)=> total += item.goods_price * item.goods_count,0)
		}
	}
}
